package com.itheima.config;

import com.itheima.commons.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * @author Tang
 * @date 2023/1/6
 */
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 配置静态资源映射
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("配置静态资源映射...");
        //通过addResourceHandler去做请求路径的映射，通过addResourceLocations去设置请求资源的路径地址
        //eg：访问http://localhost:8080/backend/index.html 就匹配上了"/backend/**"，然后就会去类路径下的/backend/目录下找index.html资源
        registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
        registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    }

    /**
     * 配置自己的对象转换器
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        //1.创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

        //2.设置具体的对象映射器
        messageConverter.setObjectMapper(new JacksonObjectMapper());

        //3.通过这是索引，让自定义的转换器放在最前面，否则默认的jackson转换器在前面，自定义的转换器就不会生效
        converters.add(0, messageConverter);
    }
}
